# handle_search_twitter.py - Handle queue requests to search Twitter.
# Copyright 2010 Rob Myers <rob@robmyers.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import datastore
import datetime
import logging
import simplejson
import terms
import traceback
import twitter
import tweet
import yaml

import wsgiref.handlers
from google.appengine.runtime import DeadlineExceededError
from google.appengine.ext import webapp

try:
    from google.appengine.api.taskqueue import Task
except:
    from google.appengine.api.labs.taskqueue import Task

class TwitterSearchWorker(webapp.RequestHandler):
    def queue_task(self, queue, handler_url, paramdict):
        '''Queue a task that goes to posterous'''
        task = Task(url=handler_url, method='POST', params=paramdict)
        task.add(queue)

    def post(self):
        dgr_yaml_path = self.request.get('dgr-yaml-path')
        yaml_stream = file (dgr_yaml_path, 'r')
        config = yaml.safe_load (yaml_stream)
        dgr_run_time_string = self.request.get('dgr-run-time')
        dgr_run_time = datetime.datetime.\
            fromtimestamp(float(dgr_run_time_string))
        twitter_username = config["twitter_username"]
        twitter_password = config["twitter_password"]
        emotion_json = self.request.get('emotions')
        emotions = simplejson.loads(emotion_json)
        if(dgr_yaml_path):
            try:
                twitter_api = twitter.Api(username = twitter_username,
                                          password = twitter_password)
                usable_tweets = \
                    tweet.twitter_any_search(emotions,
                                             exclude_retweets=True,
                                             exclude_users=[twitter_username])
                if (len (usable_tweets) > 0):
                    # Get the first usable tweet
                    first_tweet = usable_tweets[0]

                    self.queue_task('retweet-queue', '/post-retweet',
                                    {'dgr-yaml-path': dgr_yaml_path,
                                     'dgr-run-time': dgr_run_time_string,
                                     'twitter-username': twitter_username,
                                     'twitter-password': twitter_password,
                                     'tweet-id': first_tweet.tweet_id,
                                     'tweet-user': first_tweet.who,
                                     'tweet-url': first_tweet.where,
                                     'tweet-message': first_tweet.what})

                    # This should really be to/in another queue handler

                    search_terms = terms.get_terms(first_tweet.what)
                    datastore.StoreTwitterSearchResponse(dgr_yaml_path,
                                                         dgr_run_time,
                                                         first_tweet,
                                                         search_terms)
                    terms_json = simplejson.dumps(search_terms)
                    params = {'dgr-yaml-path': dgr_yaml_path,
                              'dgr-run-time': dgr_run_time_string,
                              'emotions': emotion_json,
                              'terms': terms_json}
                    
                    apikeys = yaml.safe_load (file ('./apikeys.yaml', 'r'))
                    
                    if 'flickr_api_key' in apikeys and \
                            apikeys['flickr_api_key'] != '':
                        self.queue_task('search-queue', 
                                        '/search-flickr', params)
                    if 'lastfm_api_key' in apikeys and \
                            apikeys['lastfm_api_key'] != '':
                        self.queue_task('search-queue', 
                                        '/search-lastfm', params)
                    self.queue_task('search-queue', 
                                    '/search-youtube', params)
                    self.queue_task('search-queue', 
                                    '/search-google-books', params)
                    
            except DeadlineExceededError, exc:
                # Re-throw the exception, returning an HTTP 500 result
                # This will result in this task being called again soon
                raise exc
            except Exception, e:
                logging.error(type(e))
                logging.error(e)
                logging.error(traceback.format_exc())
                # Re-throw the exception so we get called again soon
                raise e

def main():
    wsgiref.handlers.CGIHandler().run(webapp.WSGIApplication([
                ('/search-twitter', TwitterSearchWorker)], debug=True))
    
if __name__ == '__main__':
    logging.getLogger().setLevel(logging.DEBUG)
    main()
